/*
 * jrouter.c
 *
 *  Created on: Dec 8, 2010
 *      Author: fify
 */

#include "jrouter.h"
#include "device.h"
#include "jconfig.h"
#include "jsocket.h"
#include <sstream>
#include <cstdio>
#include <map>
#include <iostream>

using std::istringstream;
using std::map;
using std::cout;
using std::endl;

namespace CncrVDevice
{

void VJRouter::generate_code(int pos, string &code)
{
	ostringstream oss;

	if((int)m_cmds.size() <= pos)
		return;

	VCmd *cmd = m_cmds[pos];

	switch(cmd->m_type)
	{
	case CMD_ROUTE:
		gen_route_code((VCmdRoute*)cmd, oss);
		break;
	case CMD_INTERFACE:
		gen_interface_code((VCmdInterface*)cmd, oss);
		break;
	default:
		break;
	}

	code = oss.str();
	printf("%s\n", code.c_str());
}

void VJRouter::gen_route_code(VCmdRoute* cmd, ostringstream &oss)
{
	oss.clear();
	//printf("Genterting route code\n");
	//VEtherItf *veitf = (VEtherItf*)cmd->m_itf;
	int mask = -1;
	struct in_addr subnet;
	mask <<= (32 - cmd->m_dest.mask);
	subnet.s_addr = cmd->m_dest.ip.s_addr & htonl(mask);

	// set routing-options static route 10.200.9.0/24 next-hop em0
	oss << "set routing-options static route " << inet_ntoa(subnet) << "/";
	oss << cmd->m_dest.mask << " next-hop " << inet_ntoa(cmd->m_next_hop.ip);
}

void VJRouter::gen_interface_code(VCmdInterface *cmd, ostringstream & oss)
{
	oss.clear();
	// set interface em0 unit 0 family inet address xx.xx.xx.xx/xx
	for(unsigned i = 0;i<cmd->m_addrs.size();i++)
	{
		oss << "set interface " << "em" << cmd->m_itf->m_index << " "	// "set interface em0 "
			<< "unit 0 family inet address " << inet_ntoa(cmd->m_addrs[i].ip)	// "unit 0 family inet xx.xx.xx.xx"
			<< "/" << cmd->m_addrs[i].mask << "\r";						// "/xx\r"
	}
}

// Incomplete!
// 令JConfig进入cli的状态之后调用该函数！
int VJRouter::add_interface_ex(string &cmds, void *config)
{
	return 0;
	// mac, nitf
	map<string, int> mp_itf;
	CncrJConfig::JConfig * jconfig = (CncrJConfig::JConfig*)config;
	//JConfig::JSocket * jsock = jconfig->get_sock();

	string ip_addr, mac_addr;
	unsigned mask, nitf;

	char buf[1024];
	string temp;
	istringstream iss(cmds);

	while(iss.getline(buf, 1023) != NULL)
	{
		string cmd = string(buf);
		istringstream iss(cmd);
		iss >> temp;
		if(temp != "interface")
			continue;

		iss >> nitf >> ip_addr >> mask >> mac_addr;

		mp_itf[mac_addr] = nitf;

		while(m_itfs.size() < nitf + 1)
			m_itfs.push_back(NULL);

		m_itfs[nitf] = new VEtherItf("", this);
	}

	if(jconfig->get_status() != CncrJConfig::STATUS_CLI)
		return -1;

	string result;
	//jsock->send_msg("show interfaces");
	//jsock->recv_all(result);
	for(map<string, int>::iterator it = mp_itf.begin();it != mp_itf.end();it++)
	{
	}

	return 0;
}

} // End of namespace.

